//
//  CallCarView.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/10/10.
//

import AVFoundation
import SwiftUI
import MapKit

struct CallCarView: View {
   @State var audioPlayer: AVAudioPlayer?
   @EnvironmentObject var carOrder: CarOrder
   var service: WebSocketService

   @Binding var state: EnumCurrentState

    func makeRichText(baseText:String)->AttributedString{
    
        let plainString = "\(baseText)\("分钟以内".localized())"
        var attributedString = AttributedString(plainString)
        attributedString.foregroundColor = .black
        attributedString.backgroundColor = .clear
        //[Range<String.Index>]
        // 设置部分文本的字体和颜色
        if let range = attributedString.range(of: baseText) {
           attributedString[range].font = .system(size: 20, weight: .bold)
            attributedString[range].foregroundColor = Color.themeColor()
        }
        
        return attributedString
    }

    var body: some View {
        VStack {
            Spacer()
            VStack (spacing: 60){
                HStack {
                    Text("正在努力为您呼叫").foregroundColor(.black).font(.system(size: 18))
                    RotatingArc()
                    Spacer()
                }.padding(.horizontal,15)
                
                VStack {
                    Text(makeRichText(baseText:  "2"))
                        .frame(height: 30)
                        .font(.system(size: 14))
                    Text("预计接单时间")
                        .foregroundColor(Color.gray)
                        .font(.system(size: 14))
                }.task {
                    playCallCarSound()
                }
                Button {
                    print("cancel...")
                    stopSound()
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                        self.state = .canceling
                    }
                } label: {
                    Text("取消").foregroundColor(Color.themeColor()).frame(maxWidth: .infinity,minHeight: 48)
                }
                .background(
                    RoundedRectangle(cornerRadius: 6.0)
                        .fill(Color(hex: "#F1F3F4"))
                )
                
                .padding(.horizontal,15)
                .padding(.bottom,40)
                
//                VStack() {
//                    HStack(spacing: 60) {
//                        VStack(alignment: .leading) {
//                            Text("您周边有\(ViewModel.shared.nearCarCount)辆车").foregroundColor(.black).font(.system(size: 18))
//                            Text("请耐心等待~").foregroundColor(Color(hex: "#999999")).font(.system(size: 14)).padding(.top, 3)
//                        }.task {
//                            playCallCarSound()
//                        }
//                        Image("call_car_icon")
//                            .resizable()
//                            .frame(width: 125, height: 125)
//                    }
//                    Button {
//                        print("cancel...")
//                        stopSound()
//                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
//                            self.state = .canceling
//                        }
//                    } label: {
//                        Text("取消").foregroundColor(.white)
//                    }
//                    .frame(width: 320, height: 48)
//                    .background(
//                        RoundedRectangle(cornerRadius: 10.0)
//                            .fill(Color(hex: "FF862F8D"))
//                    )
//                }
//                .padding()
//                .background(.white)
            }
//            .padding(.horizontal,15)
            .padding(.vertical,15)
            .cornerRadius(10)
//            .shadow(radius: 2)
            .background(.linearGradient(Gradient(colors: [Color(hex: "#F8FFF8"),Color(hex: "#FCFBE4")]), startPoint: .leading, endPoint: .trailing))
            .clipShape(RoundedTopRectangle(cornerRadius: 20))
            
        }
     
    }

   func playCallCarSound() {
      print("call car, play sound ...")
      playSound(soundName: "callcar", soundType: "mp3")
   }

   func playSound(soundName: String, soundType: String) {
      if let path = Bundle.main.path(forResource: soundName, ofType: soundType) {
         do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
            audioPlayer?.numberOfLoops = -1 // 设置为无限循环
            audioPlayer?.play()
         } catch {
            print("无法找到或播放音频文件")
         }
      }
   }

   func stopSound() {
      audioPlayer?.stop()
   }
}

 struct CallCarView_Previews: PreviewProvider {
  @State var state : OrderState = OrderState.calling
    static var previews: some View {
       CallCarView(service: WebSocketService.shared, state: .constant(EnumCurrentState.calling))
          .environmentObject(CarOrder.shared)
    }
 }

struct RotatingArc: View {
    @State private var isRotating = false
    
    var body: some View {
        Circle()
            .trim(from: 0.1, to: 0.9) // 截取圆弧（从10%到90%）
            .stroke(Color.themeColor(), lineWidth: 2) // 设置线条粗细和颜色
            .frame(width: 16, height: 16) // 设置尺寸
            .rotationEffect(Angle(degrees: isRotating ? 360 : 0)) // 旋转角度
            .animation(
                Animation.linear(duration: 1.5) // 线性动画，持续1.5秒
                    .repeatForever(autoreverses: false), // 无限循环，不自反
                value: isRotating
            )
            .onAppear {
                isRotating = true // 视图出现时开始动画
            }
    }
}
